#include "JsonConfigLoader.h"
#include <SECore/Util.h>
#include "Parser.h"

namespace SEngine
{
    
    ConfigNode JsonConfigLoader::Load(const std::string &path)
    {
        Parser parser;
        parser.load(SEReadText(path));
        auto root = parser.parse();
        return Parse(root);
    }

    ConfigNode JsonConfigLoader::Parse(Json &object)
    {
        if (object.isObject()) {
            ConfigNode objNode{ConfigNode::Object()};
            for (auto & [key, value] : object.as<std::map<string, Json>>()) {
                objNode.GetValue<ConfigNode::Object>()->get()[key] = Parse(value);
            }
            return objNode;
        } else if (object.isArray()) {
            ConfigNode arrNode{ConfigNode::Array()};
            for (auto elem : object) {
                arrNode.GetValue<ConfigNode::Array>()->get().push_back(Parse(elem));
            }
            return arrNode;
        } else if (object.isBool()) {
            return ConfigNode(object.asBool());
        } else if (object.isInt()) {
            return ConfigNode(object.asInt());
        } else if (object.isDouble()) {
            return ConfigNode(object.asDouble());
        } else if (object.isString()) {
            return ConfigNode(object.asString());
        }
        return ConfigNode(ConfigNode::Null());
    }

} // namespace SEngine
